package com.jshongli.myapplication;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.FileProvider;
import android.support.v4.widget.SwipeRefreshLayout;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.jshongli.myapplication.base.BaseActivity;
import com.jshongli.myapplication.common.callback.ResponseCallback;
import com.jshongli.myapplication.common.runtimepermissions.PermissionsManager;
import com.jshongli.myapplication.common.runtimepermissions.PermissionsResultAction;
import com.jshongli.myapplication.common.utils.AccountManager;
import com.jshongli.myapplication.common.utils.AppManager;
import com.jshongli.myapplication.common.utils.ToastUtils;
import com.jshongli.myapplication.common.utils.URLUtils;
import com.jshongli.myapplication.common.utils.UtilPreferences;
import com.jshongli.myapplication.common.view.BadgeView;
import com.jshongli.myapplication.inspect.AgentmaintenanceActivity;
import com.jshongli.myapplication.inspect.InspectActivity;
import com.jshongli.myapplication.login.ChangePasswordActivity;
import com.jshongli.myapplication.login.LoginActivity;
import com.jshongli.myapplication.model.base.AppBean;
import com.jshongli.myapplication.model.base.CheckUpdate;
import com.jshongli.myapplication.task.TaskActivity;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;

public class MainActivity extends BaseActivity {

    public static final int INSTALL_PACKAGES_REQUESTCODE = 10001;

    @BindView(R.id.refresh_layout)
    SwipeRefreshLayout mRefreshLayout;
    @BindView(R.id.recy_main)
    RecyclerView mMainRecy;

    TextView tv_real_name;
    TextView tv_exit;
    TextView tv_xgmm;
    TextView tv_topname;
    RecyclerView menuRecy;
    List<String> menuList = new ArrayList<>();
    BaseQuickAdapter<String, BaseViewHolder> menuAdapter;

    private BaseQuickAdapter<AppBean, BaseViewHolder> mMainAdapter;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView() {
        super.initView();
        mToolbar.setVisibility(View.GONE);

        requestPermissions();

        checkUpdate();

        initMainAdapter();

        mRefreshLayout.setColorSchemeResources(R.color.refresh_blue,
                R.color.refresh_red, R.color.refresh_blue, R.color.refresh_red);
        mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mRefreshLayout.setRefreshing(false);

            }
        });

    }

    @Override
    protected void initData() {
        super.initData();
        List<String> menulist = new ArrayList<>();
        menulist.add("巡检巡查");
        menulist.add("代维事件");
        menuList = menulist;

    }

    //region 权限请求
    @TargetApi(23)
    private void requestPermissions() {
        PermissionsManager.getInstance().requestPermissionsIfNecessaryForResult(this,
                new String[]{Manifest.permission.REQUEST_INSTALL_PACKAGES,Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.ACCESS_FINE_LOCATION},
                new PermissionsResultAction() {
                    @Override
                    public void onGranted() {

                    }

                    @Override
                    public void onDenied(String permission) {
                    }
                });


    }
    //endregion

    private void initMainAdapter() {
        mMainAdapter = new BaseQuickAdapter<AppBean, BaseViewHolder>(R.layout.list_home_item) {
            @Override
            protected void convert(BaseViewHolder helper, AppBean item) {
            }
        };

        //region top
        View headerView = LayoutInflater.from(mContext).inflate(R.layout.home_top, null);
        tv_topname  = headerView.findViewById(R.id.topname);
        PackageInfo packageInfo = null;
        try {
            packageInfo = mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        String version = packageInfo.versionName;
        tv_topname.setText("苏浙沪长线代维管理系统"+"V"+ version);
        tv_real_name = headerView.findViewById(R.id.tv_real_name);
        tv_real_name.setText(AccountManager.getRealName());
        tv_exit = headerView.findViewById(R.id.exit);
        tv_exit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                UtilPreferences.removeKey(mContext, getResources().getString(R.string.token));
                AppManager.finishAllActivity();
                openActivity(LoginActivity.class, true);
            }
        });
        tv_xgmm = headerView.findViewById(R.id.xgmm);
        tv_xgmm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                openActivity(ChangePasswordActivity.class, false);
            }
        });
        menuRecy = headerView.findViewById(R.id.recy);

        mMainAdapter.addHeaderView(headerView, 0);
        //endregion

        mMainAdapter.setHeaderAndEmpty(true);
        mMainRecy.setAdapter(mMainAdapter);
        mMainRecy.setLayoutManager(new LinearLayoutManager(mContext));
        mMainRecy.setItemAnimator(new DefaultItemAnimator());

        initMenuAdapter();

    }

    //region init - menuAdapter 菜单
    private void initMenuAdapter() {
        menuAdapter = new BaseQuickAdapter<String, BaseViewHolder>(R.layout.list_menu_item, menuList) {
            @Override
            protected void convert(BaseViewHolder helper, String item) {
                helper.setText(R.id.txt, item);
                BadgeView bv_num = helper.getView(R.id.bv_num);
                helper.setImageResource(R.id.img, home_menu_img(item));
            }
        };
        menuAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                String name = menuList.get(position);
                menuClick(name);
            }
        });
        menuRecy.setAdapter(menuAdapter);
        menuRecy.setLayoutManager(new GridLayoutManager(mContext, 2));
        menuRecy.setItemAnimator(new DefaultItemAnimator());


    }
    //endregion

    //region click - 菜单栏
    private void menuClick(String name) {
        Bundle bundle = new Bundle();
        switch (name) {
            case "巡检巡查":
                openActivity(InspectActivity.class, false);
                break;
            case "代维事件":
//                openActivity(TaskActivity.class, false);
                openActivity(AgentmaintenanceActivity.class, false);

                break;

        }
    }

    public static int home_menu_img(String name) {
        int res;
        if (!TextUtils.isEmpty(name)) {
            if (name.equals("巡检巡查")) {
                res = R.mipmap.menu7;
            }  else if (name.equals("代维事件")) {
                res = R.mipmap.menu8;
            } else {
                res = R.mipmap.default_img;
            }
        } else {
            res = R.mipmap.default_img;
        }
        return res;
    }
    //endregion

    //region 版本 -- 检查更新
    public void checkUpdate() {
        String url = URLUtils.URLNoToken("manageAPI/sysApp/getLast");

        OkHttpUtils
                .get()
                .url(url)
                .addHeader("Authorization", AccountManager.getToken())
                .build()
                .execute(new ResponseCallback<CheckUpdate>(mContext) {//400 登录超时
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(final CheckUpdate mCheckUpdate, int id) {

                        if (mCheckUpdate.data != null) {
                            PackageInfo packageInfo = null;

                            try {
                                packageInfo = mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0);
                            } catch (PackageManager.NameNotFoundException e) {
                                e.printStackTrace();
                            }

                            int version = packageInfo.versionCode;

                            if (mCheckUpdate.data!=null && (Integer) (mCheckUpdate.data.versionCode) != null) {
                                if (mCheckUpdate.data.versionCode > version) {
                                    downloadUrl = mCheckUpdate.data.downloadUrl;
                                    download();
                                }
                            }
                        }

                    }
                });
    }
    //endregion

    //region 版本 -- 安装
    private ProgressDialog pd;  // 下载apk进度条
    private String downloadUrl; // 下载apk url
    private File mInstallPackage;

    private void download() {

        pd = new ProgressDialog(mContext);
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.setMessage("正在更新软件...");
        pd.setCancelable(false);
        pd.show();

        OkHttpUtils
                .get()
                .url(downloadUrl)
                .build()
                .execute(new FileCallBack(Environment.getExternalStorageDirectory().getAbsolutePath(), "苏浙沪干线维护.apk") {

                    @Override
                    public void inProgress(float progress, long total, int id) {
                        pd.setProgress((int) (100 * progress));
                        if (progress == 1) {
                            pd.dismiss();
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        pd.dismiss();
                        ToastUtils.show(mContext, "出错了");
                    }

                    @Override
                    public void onResponse(File file, int id) {
                        mInstallPackage = file;
                        checkIsAndroidOAndInstall();
                    }

                });

    }

    //安装apk
    protected void installApk() {
//        if (mInstallPackage != null) {
//            Intent intent = new Intent();
//            //执行动作
//            intent.setAction(Intent.ACTION_VIEW);
//            //执行的数据类型
//            intent.setDataAndType(Uri.fromFile(mInstallPackage), "application/vnd.android.package-archive"); // 编者按：此处Android应为android，否则造成安装不了
//            startActivity(intent);
//        }
        if (mInstallPackage != null) {
            Intent intent = new Intent();
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setAction(Intent.ACTION_VIEW);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                Uri apkUri = FileProvider.getUriForFile(mContext.getApplicationContext(), BuildConfig.APPLICATION_ID + ".provider", mInstallPackage);
                intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            } else {
                intent.setDataAndType(Uri.fromFile(mInstallPackage), "application/vnd.android.package-archive");
            }
            mContext.startActivity(intent);
        }

    }

    /**
     * 判断是否是8.0,8.0需要处理未知应用来源权限问题,否则直接安装
     */
    private void checkIsAndroidOAndInstall() {
        if (Build.VERSION.SDK_INT >= 26) {
            boolean b = getPackageManager().canRequestPackageInstalls();
            if (b) {
                installApk();
            } else {
                // 请求安装未知应用来源的权限
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.REQUEST_INSTALL_PACKAGES}, INSTALL_PACKAGES_REQUESTCODE);
            }
        } else {
            installApk();
        }

    }

    //endregion

    //region 权限回调

    public static final int GET_UNKNOWN_APP_SOURCES = 10002;
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case INSTALL_PACKAGES_REQUESTCODE:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    installApk();
                } else {
                    Uri packageURI = Uri.parse("package:" + getPackageName());
                    Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI);
                    startActivityForResult(intent, GET_UNKNOWN_APP_SOURCES);
                }
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case GET_UNKNOWN_APP_SOURCES:
                checkIsAndroidOAndInstall();
                break;
        }
    }

    //endregion


}